package com.dkd.app.service.impl;

import cn.elegent.pay.CallBackService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.dkd.app.domain.Order;
import com.dkd.app.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;

@Service
@Slf4j
public class CallBackServiceImpl implements CallBackService {


    @Autowired
    private OrderService orderService;

    @Override
    public void successPay(String orderSn) {
        log.info("支付成功回调！订单号: {}", orderSn);
        updateOrderStatus(orderSn, 1, 1); // 设置订单状态为支付完成，支付状态为支付完成
    }

    @Override
    public void failPay(String orderSn) {
        log.info("支付失败回调！订单号: {}", orderSn);
        updateOrderStatus(orderSn, 4, 0); // 设置订单状态为已取消，支付状态为未支付
    }

    @Override
    public void successRefund(String orderSn) {
        log.info("退款成功回调！订单号: {}", orderSn);
        updateOrderStatus(orderSn, null, 3); // 不改变订单状态，仅设置支付状态为退款完成
    }

    @Override
    public void failRefund(String orderSn) {
        log.info("退款失败回调！订单号: {}", orderSn);
        updateOrderStatus(orderSn, null, 2); // 不改变订单状态，仅设置支付状态为退款中
    }

    /**
     * 更新订单状态和支付状态
     */
    private void updateOrderStatus(String orderNo, Integer status, Integer payStatus) {
        try {
            LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Order::getOrderNo, orderNo);

            if (status != null) {
                updateWrapper.set(Order::getStatus, status);
            }
            if (payStatus != null) {
                updateWrapper.set(Order::getUpdateTime, payStatus);
            }
            updateWrapper.set(Order::getUpdateTime, LocalDate.now());

            boolean rowsAffected = orderService.update(null, updateWrapper);
            if (rowsAffected) {
                log.info("订单 {} 状态已更新", orderNo);
            } else {
                log.warn("未找到需要更新的订单：{}", orderNo);
            }
        } catch (Exception e) {
            log.error("更新订单 {} 状态失败: {}", orderNo, e.getMessage(), e);
            throw new RuntimeException("更新订单状态失败");
        }
    }
}